package com.lvmama.rhino.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.base.BaseControllerSupport;
import com.lvmama.rhino.enums.CommonParentType;
import com.lvmama.rhino.pojo.PositionAnalysis;
import com.lvmama.rhino.pojo.StatisticCode;
import com.lvmama.rhino.service.PositionAnalysisService;
import com.lvmama.rhino.service.StatisticCodeService;
import com.lvmama.rhino.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("positionAnalysis")
public class PositionAnalysisController extends BaseControllerSupport {

	@Autowired
	private StatisticCodeService statisticCodeService;

	@Autowired
	private PositionAnalysisService positionAnalysisService;

	@RequestMapping("positionTree")
	public String topicTree(ModelMap model) {
		return "application/positionAnalysis/positionTree";
	}

	/**
	 * @Title: queryList
	 * @Description: 坑位列表
	 * @param @param platform
	 * @param @param chooseTime
	 * @param @param code
	 * @param @return
	 * @param @throws Exception 设定文件
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping("queryList")
	@ResponseBody
	public Map<String, Object> queryList(
			@RequestParam("platform") String platform, @RequestParam("chooseTime") String chooseTime,
			@RequestParam("pageName") String pageName,int pageCurrentNum, int pageSize) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		PositionAnalysis pit = new PositionAnalysis();
		// 查询日期条件处理
		Map<String, Date> dateMap = getQueryDate(chooseTime);
		Date beginDate = dateMap.get("beginDate");
		Date endDate = dateMap.get("endDate");
		pit.setStartDate(beginDate);
		pit.setEndDate(endDate);
		pit.setPage_size(pageSize);
		pit.setCurrentPage(pageCurrentNum);
		if (StringUtils.isNotEmpty(platform)) {
			List<String> statisticCodeList = new ArrayList<String>();
			String[] platforms = StringUtils.split(platform,",");
			for(String pf:platforms){
				statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
			}
			pit.setStatisticCodeList(statisticCodeList);
		}
		pit.setPageName(pageName);
		PageInfo<PositionAnalysis> page = positionAnalysisService
				.getPitList(pit);
		resultMap.put("page", page);
		return resultMap;
	}

	/**
	 * 图表数据
	 * 
	 * @param platform
	 * @param chooseTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("chartData")
	@ResponseBody
	public Map<String, Object> chartData(
			@RequestParam("platform") String platform, @RequestParam("chooseTime") String chooseTime,
			@RequestParam("code") String code,@RequestParam("pageName") String pageName) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		PositionAnalysis pit = new PositionAnalysis();
		// 查询日期条件处理
		Map<String, Date> dateMap = getQueryDate(chooseTime);
		Date beginDate = dateMap.get("beginDate");
		Date endDate = dateMap.get("endDate");
		pit.setStartDate(beginDate);
		pit.setEndDate(endDate);
		pit.setCode(code);
		if (StringUtils.isNotEmpty(platform)) {
			List<String> statisticCodeList = new ArrayList<String>();
			String[] platforms = StringUtils.split(platform,",");
			for(String pf:platforms){
				statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
			}
			pit.setStatisticCodeList(statisticCodeList);
		}
		pit.setPageName(pageName);
		pit.setPlatform("pit");
		List<PositionAnalysis> pitListByCategory = positionAnalysisService
				.getPitListByCategory(pit);
		List<PositionAnalysis> pitListByDate = positionAnalysisService
				.getPitListByDate(pit);
		List<PositionAnalysis> pitBarByCategory = positionAnalysisService
				.getPitBarByCategory(pit);
		// 总订单量 总订单金额
		int payAmountTotal = 0;
		double payMoneyTotal = 0;

		// 饼状图数据
		JSONArray payAmountArr = new JSONArray();
		JSONArray payMoneyArr = new JSONArray();
		for (PositionAnalysis positionAnalysis : pitListByCategory) {
			if(positionAnalysis ==null || positionAnalysis.getPayMoney()==null){
				continue;
			}
			payAmountTotal += positionAnalysis.getPayAmount();
			payMoneyTotal += positionAnalysis.getPayMoney();
			JSONObject payAmountOb = new JSONObject();
			payAmountOb.put("categoryName",CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
			payAmountOb.put("amount",positionAnalysis.getPayAmount());
			payAmountArr.add(payAmountOb);
			JSONObject payMoneyOb = new JSONObject();
			payMoneyOb.put("categoryName",CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
			payMoneyOb.put("amount",positionAnalysis.getPayMoney());
			payMoneyArr.add(payMoneyOb);
		}
		// 柱状图数据
		List<String> categoryNames = new ArrayList<>();
		JSONArray arr2 = new JSONArray();
		for (PositionAnalysis positionAnalysis : pitBarByCategory) {
			String categoryName = CommonParentType
					.getCategoryShowName(positionAnalysis.getCategoryId());
			if(StringUtils.isNotEmpty(categoryName)){
				categoryNames.add(categoryName);
				JSONObject o = new JSONObject();
				o.put("categoryName",categoryName);
				o.put("amount",positionAnalysis.getCompletedPaymentPageSum()
						+ positionAnalysis.getDetailPageSum()
						+ positionAnalysis.getFillOrderPageSum()
						+ positionAnalysis.getPendingPaymentPageSum());
				arr2.add(o);
			}
			
		}

		// 折线图数据
		String[] dateAxis = DateUtil.getBetweenTime(beginDate, endDate,
				"yyyy/MM/dd");
		List<String> dateList = Arrays.asList(dateAxis);
		JSONArray arr = new JSONArray();
		for(String date:dateList){
			for (String category : categoryNames) {
				Integer amount= 0;
				for (PositionAnalysis position : pitListByDate) {
					String categoryName = CommonParentType
							.getCategoryShowName(position.getCategoryId());
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
					String time = sdf.format(position.getTime());
					if (category.equals(categoryName) && date.equals(time)) {
						amount += position.getCompletedPaymentPageSum()
								+ position.getDetailPageSum()
								+ position.getFillOrderPageSum()
								+ position.getPendingPaymentPageSum();
					}
				}
				JSONObject o = new JSONObject();
				o.put("categoryName",category);
				o.put("time",date);
				o.put("amount",amount);
				arr.add(o);
			}
		}
		resultMap.put("payAmountTotal", payAmountTotal);
		resultMap.put("payMoneyTotal", payMoneyTotal);
		resultMap.put("jsonData",arr);
		resultMap.put("jsonData2",arr2);
		resultMap.put("payAmountJsonData",payAmountArr);
		resultMap.put("payMoneyJsonData",payMoneyArr);
		return resultMap;
	}

	/**
	 * @Title: getPageChartData
	 * @Description: 根据品类获取相关页面的引流
	 * @param @param platform
	 * @param @param chooseTime
	 * @param @param category_id
	 * @param @return
	 * @param @throws Exception 设定文件
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping("getPageChartData")
	@ResponseBody
	public Map<String, Object> getPageChartData(
			@RequestParam("platform") String platform, @RequestParam("chooseTime") String chooseTime,
			@RequestParam("category_name") String category_name, @RequestParam("pageName") String pageName)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		PositionAnalysis pit = new PositionAnalysis();
		// 查询日期条件处理
		Map<String, Date> dateMap = getQueryDate(chooseTime);
		Date beginDate = dateMap.get("beginDate");
		Date endDate = dateMap.get("endDate");
		pit.setStartDate(beginDate);
		pit.setEndDate(endDate);
		if (StringUtils.isNotEmpty(platform)) {
			List<String> statisticCodeList = new ArrayList<String>();
			String[] platforms = StringUtils.split(platform,",");
			for(String pf:platforms){
				statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
			}
			pit.setStatisticCodeList(statisticCodeList);
		}
		pit.setPageName(pageName);
		pit.setPlatform("pit");
		pit.setCategoryId(CommonParentType
				.getCategoryValueByShowName(category_name));
		PositionAnalysis pitForPage = positionAnalysisService
				.getPageNumByCategory(pit);
		resultMap.put("pitForPage", pitForPage);
		return resultMap;
	}

	/**
	 * @Title: getQueryDate
	 * @Description: 查询条件起始时间的处理
	 * @param @param choose_date
	 * @param @return 设定文件
	 * @return Map<String,Date> 返回类型
	 * @throws
	 */
	private Map<String, Date> getQueryDate(String choose_date) {
		Map<String, Date> map = new HashMap<>();
		DateTimeFormatter formater = DateTimeFormat
				.forPattern("MM/dd/yyyy HH:mm:ss");
		Date beginDate = DateTime.parse(
				choose_date.split("-")[0].trim() + " 00:00:00", formater)
				.toDate();
		Date endDate = DateTime.parse(
				choose_date.split("-")[1].trim() + " 23:59:59", formater)
				.toDate();
		map.put("beginDate", beginDate);
		map.put("endDate", endDate);
		return map;
	}

	/**
	 * 根据平台获得版本类型
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("appVersion")
	@ResponseBody
	public Map<String, Object> queryAppVersion(String platForm) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 根据code码获得其子级的code码信息
		List<StatisticCode> codeList = statisticCodeService.getLikeCodeObj("2");
		if (platForm != "") {
			for (StatisticCode statisticCode : codeList) {
				if (statisticCode.getName().startsWith(platForm)) {
					Map<String, Object> map = new HashMap<String, Object>();
					String appVersionName = statisticCode.getName().replace(
							platForm, "");
					map.put("name", appVersionName);
					map.put("value", statisticCode.getCode());
					list.add(map);
				}
			}
		}
		result.put("code", "1");
		result.put("msg", list);
		return result;
	}
}
